// 前进
void handleForward(){
  digitalWrite(6, HIGH);
  digitalWrite(7, LOW);
  digitalWrite(8, HIGH);
  digitalWrite(9, LOW);
}

// 后退
void handleFallback(){
  digitalWrite(6, LOW);
  digitalWrite(7, HIGH);
  digitalWrite(8, LOW);
  digitalWrite(9, HIGH);
}

// 左转
void handleTurnLeft(){
  digitalWrite(6, HIGH);
  digitalWrite(7, LOW);
  digitalWrite(8, LOW);
  digitalWrite(9, HIGH);
}

// 右转
void handleTurnRight(){
  digitalWrite(6, LOW);
  digitalWrite(7, HIGH);
  digitalWrite(8, HIGH);
  digitalWrite(9, LOW);
}

// 停止
void handleStop(){
  digitalWrite(6, HIGH);
  digitalWrite(7, HIGH);
  digitalWrite(8, HIGH);
  digitalWrite(9, HIGH);
}

// 处理动作
void handleMotorAction(char commend){
  if(commend == '\n' || commend == '\r'){
    return;
  }
  Serial.print("commend:");
  Serial.print(commend);
  Serial.println();

  switch (commend){
    case 'w':
        // 如果指令为前进
        handleForward();
        break;
    case 's':
        // 如果指令为后退
        handleFallback();
        break;
    case 'a':
        // 如果指令为左转
        handleTurnLeft();
        break;
    case 'd':
        // 如果指令为右转
        handleTurnRight();
        break;
    case 'q':
        // 如果指令为停止
        handleStop();
        break;
    default:
        // 如果不匹配任何指令 不进行操作
        break;
  }
}

void setup() {
  // put your setup code here, to run once:
  // 初始化串口
  Serial.begin(115200);
  // 定义6、7、8、9引脚模式
  pinMode(6, OUTPUT);
  pinMode(7, OUTPUT);
  pinMode(8, OUTPUT);
  pinMode(9, OUTPUT);
  // 初始化时履带为停止状态 所以给6、7、8、9引脚输出高电平
  digitalWrite(6, HIGH);
  digitalWrite(7, HIGH);
  digitalWrite(8, HIGH);
  digitalWrite(9, HIGH);
}

void loop() {
  // put your main code here, to run repeatedly:
  // 如果串口接收到了控制指令则读取指令并做出相应的动作
  if (Serial.available() > 0) {
    char commend =  Serial.read();
     handleMotorAction(commend);
  }
}